from django.db import transaction
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer

from py_web.security.models import User, UserRole, Menu, Role, RoleMenu


# 用户表
class UserSerializer(ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

    # 保证新增用户时密码以密文存储，同时增加用户角色中间表数据
    @transaction.atomic
    def create(self, validated_data):
        user = User(**validated_data)
        user.set_password(validated_data["password"])
        user.save()

        # 添加用户角色关联关系
        roleIds = self.initial_data['roleId']
        if roleIds is not None and len(roleIds) > 0:
            for roleId in roleIds:
                data = {"userId": user.pk, "roleId": roleId}
                serializer = UserRolesSerializer(data=data)
                serializer.is_valid(raise_exception=True)
                serializer.save()

        return user


# 用户和角色关联表
class UserRolesSerializer(ModelSerializer):
    class Meta:
        model = UserRole
        fields = '__all__'


# 菜单权限表
class MenuSerializer(ModelSerializer):
    class Meta:
        model = Menu
        fields = '__all__'


class MenuTreeselectSerializer(ModelSerializer):
    label = serializers.CharField(source='menuName')

    class Meta:
        model = Menu
        fields = ('menuId', 'menuName','label', 'parentId', 'menuType')





# 角色信息表
class RoleSerializer(ModelSerializer):
    class Meta:
        model = Role
        fields = '__all__'


# 角色和菜单关联表
class RoleMenuSerializer(ModelSerializer):
    class Meta:
        model = RoleMenu
        fields = '__all__'
